<?php
declare(strict_types=1);
namespace Haozing\Core\Exception\Handler;


use Haozing\Core\Constants\ErrorCode;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class CommonExceptionHandler extends ExceptionHandler
{
    public function __construct(protected StdoutLoggerInterface $logger)
    {
    }

    public function handle(Throwable $throwable, ResponseInterface $response): \Psr\Http\Message\MessageInterface|ResponseInterface
    {
        $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
        $this->logger->error($throwable->getTraceAsString());
        ## 格式化输出
        $data     = responseDataFormat($throwable->getCode(), $throwable->getMessage());
        $httpCode = ErrorCode::getHttpCode($data['code']);
        $dataStream = new SwooleStream(json_encode($data, JSON_UNESCAPED_UNICODE));
        ## 阻止异常冒泡
        $this->stopPropagation();
        return $response->withHeader('Server', 'fast-core')
            ->withAddedHeader('Content-Type', 'application/json;charset=utf-8')
            ->withStatus($httpCode)
            ->withBody($dataStream);
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}